package countDownLatch;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * Created by IntelliJ IDEA.
 * User: liuliwei
 * Date: 2017-09-26
 * Time: 下午3:50
 * Description: 线程池版本
 */
public class CountDownLatchTest2 {
    public static void main(String[] args) throws InterruptedException {

        int total = 300;
        CountDownLatch doneSignal = new CountDownLatch(total);
//        Executor executor = Executors.newFixedThreadPool(3);
//        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        ThreadFactory threadFactory;
        threadFactory = new ThreadFactoryBuilder().setNameFormat("llw-pool-%d").build();
        Executor executor = Executors.newSingleThreadExecutor(threadFactory);

        for (int i = 0; i < total; i++) {
            executor.execute(new Worker2(doneSignal,i));
        }

        doneSignal.await();//是否等待
        System.out.println("current thread" + Thread.currentThread());
    }
}


class Worker2 implements Runnable {
    private final CountDownLatch doneSignal;
    private final int i;

    public Worker2(CountDownLatch doneSignal, int i) {
        this.doneSignal = doneSignal;
        this.i = i;
    }

    @Override
    public void run() {
        doWork(i);
        doneSignal.countDown();
    }

    private void doWork(int i) {
        System.out.println(Thread.currentThread()+"--->"+i);
    }
}

